package App.Service;

import App.Model.Account.CrmUser;
import App.Model.BaseEnum;
import App.Model.Chat.CrmChatGroup;
import App.Model.Chat.CrmChatGroupPart;
import App.Model.Export.*;
import App.Model.PageSummary;
import App.Model.Project.*;
import App.Model.Task.CrmTask;
import App.Model.Task.CrmTaskMember;
import App.Model.Task.GetTaskPageItemsRequest;
import App.Model.Task.ResultResponse;
import App.Repository.CommonRepository;
import App.Repository.ProjectRepository;
import App.Utility.CommonHelper;
import App.Utility.DateUtil;
import App.Utility.HtmlFieldMapInfo;
import App.Utility.WordPrintUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by xw on 2018/11/20.
 */

@Service
public class ProjectService {
    @Autowired
    private CommonHelper _commonHelper;

    @Autowired
    private ProjectRepository _repository;

    @Resource
    private TecentIMService _imService;


    @Autowired
    private CommonRepository _commonRepository;


    public Map<String, Object> saveProject(ProjectSaveRequest _request, int userId) throws Exception {

        //如果projectid为null那么就是新增，否则为更新
        String _projectid = _request.getProjectid();
        if (_projectid != null && !_projectid.isEmpty()) {
            return _repository.updateProject(_request, userId);
        } else {
            List<String> _groupids = new ArrayList<>();
            Map<String, List<String>> map = new HashMap<>();
            Map<String, Object> res = _repository.insertProject(_request, _groupids, userId, map);

            int count = (int) res.get("result");
            if (count > 0) {
                //是否是商城过来的消息
                if (1 == _request.getIsShop()) {
                    //委托人发送消息
                    if (map.get("client").size() > 0) {
                        _repository.sendIMMessage(map.get("client"), _request.getClintMsg(), userId, 0);
                    }

                    //律师团队过来的消息
                    if (map.get("member").size() > 0) {
                        _repository.sendIMMessage(map.get("member"), _request.getMemberMsg(), userId, 0);
                    }
                } else {
                    String _messageTemplate = "%s新建了本项目";
                    CrmUser _theUser = _commonRepository.getUserInfo(userId);
                    String _theUserName = "";
                    if (_theUser != null) {
                        _theUserName = _theUser.getRealname();
                    }
                    String _message = String.format(_messageTemplate, _theUserName);
                    _repository.sendIMMessage(_groupids, _message, userId, 0);
                }
            }
            return res;
        }
    }

    public List<ProjectList> getProjectlist(ProjectGetListRequest _request, int userid, String forType) {
        return _repository.getProjectList(_request, userid, forType);
    }

    public ProjectDetailResponse detail(String id, int userid,String device) {
        return _repository.getProjectDeail(id, userid,device);
    }

    public List<CrmProjectStage> getProjectStages(ProjectStageGetRequest _request) {
        return _repository.getProjectStages(_request);
    }

    public List<CrmProjectCourt> getProjectCourts(ProjectCourtGetRequest _request) {
        return _repository.getProjectCourts(_request);
    }

    public List<ProjectCause> getProjectCause(ProjectCaseGetRequest _request) {
        return _repository.getProjectCause(_request);
    }

    public List<ProjectFolderResponse> getProjectFolder(ProjectFolderGetRequest _request, int userid) {
        List<ProjectFolderResponse> _result = _repository.getTempFolder(_request, userid);
        return _result;
    }

    public List<ProjectFolderResponse> getProjectTaskFolder(ProjectTaskFolderGetRequest _request, int userid) {
        List<ProjectFolderResponse> _result = _repository.getProjectTaskFolder(_request, userid);
        return _result;
    }


    private ProjectFolder toProjectFolder(CrmProjectFolder folder) {
        ProjectFolder _folder = new ProjectFolder();
        _folder.setRecid(folder.getRecid());
        _folder.setRecname(folder.getPrefixname() + folder.getRecname());
        return _folder;

    }

    public List<CrmProjectDefaultFolder> getProjectDefaultFolder(ProjectFolderGetRequest _request) {
        return _repository.getProjectDefaultFolder(_request);
    }

    public ProjectChatResponse getProjectChatInfo() {
        return _repository.getProjectChatInfo();
    }

    public int saveGroupTopicHistory(ProjectTopicCheckRequest _request, int userid) {
        // return  _repository.saveGroupTopicHistory(_request);

        return 0;
    }

    @Transactional
    public int addMember(ProjectMemberAddRequest _request, int userid) {

        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        int _groupType = _request.getGrouptype();
        List<ProjectMember> _members = _request.getMembers();


        List<CrmProjectMember> _projectStageMembers = _commonRepository.getProjectStagetMember(_projectid, _stageid, userid);
        if (_projectStageMembers != null) {
            long _theCount = _projectStageMembers.stream().filter(x -> x.getUserid() == userid && (x.getIsmanager() || x.ishost())).count();
            if (_theCount == 0) {
                //no add meber permission
                return -1;
            }
        }

        List<ProjectMember> _newMembers = new ArrayList<>();
        for (ProjectMember m : _members) {
            long _theCount = _projectStageMembers.stream().filter(x -> x.getUserid() == m.getUserid() && x.getGrouptype() == m.getGrouptype()).count();
            if (_theCount == 0) {
                _newMembers.add(m);
            }
        }


        String _groupid = _repository.getProjectGroupId(_projectid, _stageid, _groupType);
        List<CrmProjectClient> _clients = _repository.getProjectClient(_projectid);
        String _clientId = "";
        if (_clients != null) {
            Optional<CrmProjectClient> _theClient = _clients.stream().filter(x -> x.getStageid() == _stageid).findFirst();
            if (_theClient.isPresent()) {
                _clientId = _theClient.get().getRecid();
            }
        }

        int _result = 0;
        if (_members != null) {
            for (ProjectMember m : _newMembers) {
                _result = _repository.insertProjectMemberSingle(_projectid, _stageid, _groupid, m, _clientId, userid);
            }
        }

        if (_result > 0) {
            List<Integer> _useridList = new ArrayList<>();
            for (ProjectMember _member : _newMembers) {
                int _memberid = _member.getUserid();
                _useridList.add(_memberid);
            }
            boolean _isSuccess = _imService.addIMGroupMember(_groupid, _useridList, userid);
            if (!_isSuccess) {
                // _result = 0;
            }

            //new Thread(() -> {
            //send system message
            List<String> _groupids = new ArrayList<String>();
            List<CrmChatGroupPart> _groups = _repository.getProjectChatGroup(_projectid);

            //int _theChatGroupType=0;

            boolean _isLawyerMember = false;
            if (_members.get(0).getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()) {
                _isLawyerMember = true;
            } else {
                _isLawyerMember = false;
            }

            if (_groups != null && _groups.size() > 0) {
                List<CrmChatGroupPart> _theGrous = _groups.stream().filter(x -> x.getStageid() == _stageid
                        && x.getChattype() == BaseEnum.ChatType.Project.getChatType()).collect(Collectors.toList());

                //如果添加的是律师协作团队的人，消息仅仅发送到律师协作团队聊天组
                if (_isLawyerMember) {
                    _groupids = _theGrous.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType())
                            .map(CrmChatGroupPart::getGroupid)
                            .collect(Collectors.toList());
                } else {
                    _groupids = _theGrous.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                }
            }

            String userIds = _newMembers.stream().map(ProjectMember::getUseridStr).collect(Collectors.joining(","));
            String names = _commonRepository.getUserListByIds(userIds).stream().map(CrmUser::getRealname).collect(Collectors.joining(","));
            String desStr = "";
            if (_isLawyerMember)
                desStr = "到律师协作团队";
            else {
                ProjectMember m = _newMembers.get(0);
                if (m.getInnergrouptype() == 1) { //委托人组
                    desStr = "到委托人协作团队-委托人组";
                } else if (m.getInnergrouptype() == 2) {
                    desStr = "到委托人协作团队-律师代理组";
                }
            }
            //用户姓名上传了/删除了/重命名了文件；
            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            String _content = String.format("%s添加了成员：%s%s", _theUser.getRealname(), names, desStr);
            if (_groupids != null && _groupids.size() > 0) {
                _repository.sendIMMessage(_groupids, _content, userid, 1);
            }

            //  }).start();

        }
        return _result;
    }

    public ResultResponse deleteMember(ProjectMemberDeleteRequest _request, int userid) {

        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        int _groupType = _request.getGrouptype();
        List<String> _taskNames = new ArrayList<>();
        List<String> _messages = new ArrayList<>();
        List<ProjectMember> _deleteMembers = _request.getMembers();


        ResultResponse _resultResponse = new ResultResponse();

        List<CrmProjectMember> _projectStageMembers = _commonRepository.getProjectStagetMember(_projectid, _stageid, userid);
        if (_projectStageMembers != null) {
            long _theCount = _projectStageMembers.stream().filter(x -> x.getUserid() == userid && (x.getIsmanager() || x.ishost())).count();
            if (_theCount == 0) {

                //no add meber permission
                _resultResponse.setResultcode(-2);
                _resultResponse.setMessage("没有删除成员的权限");
                return _resultResponse;
            }
        }

        List<CrmTask> _tasks = _commonRepository.getTaskByProjectStage(_projectid, _stageid);
        if (_tasks != null && _tasks.size() > 0) {
            for (ProjectMember m : _deleteMembers) {
                _taskNames.clear();
                for (CrmTask t : _tasks) {
                    List<CrmTaskMember> _members = _commonRepository.getTaskMembers(t.getRecid());
                    long _theCount = _members.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                    if (_theCount > 0) {
                        _taskNames.add(t.getContent());
                    }
                }
                if (_taskNames.size() > 0) {
                    String _taskName = org.apache.commons.lang.StringUtils.join(_taskNames.toArray(), ",");
                    CrmUser _user = _commonRepository.getUserInfo(m.getUserid());
                    String _userName = "";
                    if (_user != null) {
                        _userName = _user.getRealname();
                    }
                    String _theMessage = String.format("请先将%s从任务%s中删除!", _userName, _taskName);
                    _messages.add(_theMessage);
                }
            }
        }


        if (_messages.size() > 0) {
            String _finalMessage = org.apache.commons.lang.StringUtils.join(_messages.toArray(), ",");
            _resultResponse.setResultcode(-1);
            _resultResponse.setMessage(_finalMessage);
            return _resultResponse;
        }


        String _groupid = _repository.getProjectGroupId(_projectid, _stageid, _groupType);
        int _result = _repository.deleteMember(_request, _groupid, userid);
        if (_result > 0) {

            List<Integer> _useridList = new ArrayList<>();
            for (ProjectMember _member : _request.getMembers()) {
                int _memberid = _member.getUserid();
                _useridList.add(_memberid);
            }
            boolean _isSuccess = _imService.removeIMGroupMember(_groupid, _useridList, userid);
            if (!_isSuccess) {
                _result = 0;
            }

            boolean _isLawyerMember = false;
            if (_deleteMembers.get(0).getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()) {
                _isLawyerMember = true;
            } else {
                _isLawyerMember = false;
            }

            // todo: send message
            // new Thread(() -> {
            List<String> _groupids = new ArrayList<String>();
            List<CrmChatGroupPart> _groups = _repository.getProjectChatGroup(_projectid);
            if (_groups != null && _groups.size() > 0) {
                List<CrmChatGroupPart> _theGrous = _groups.stream().filter(x -> x.getStageid() == _stageid
                        && x.getChattype() == BaseEnum.ChatType.Project.getChatType()).collect(Collectors.toList());
                if (_isLawyerMember) {
                    _groupids = _theGrous.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType())
                            .map(CrmChatGroupPart::getGroupid)
                            .collect(Collectors.toList());
                } else {
                    _groupids = _theGrous.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
                }
            }

            String userIds = StringUtils.join(_deleteMembers.stream().map(ProjectMember::getUseridStr).toArray(), ",");
            ;
            String names = _commonRepository.getUserListByIds(userIds).stream().map(CrmUser::getRealname).collect(Collectors.joining(","));
            String desStr = "";
            if (_isLawyerMember)
                desStr = " 律师协作团队";
            else {
                ProjectMember m = _deleteMembers.get(0);
                if (m.getInnergrouptype() == 1) { //委托人组
                    desStr = " 委托人协作团队-委托人组";
                } else if (m.getInnergrouptype() == 2) {
                    desStr = " 委托人协作团队-律师代理组";
                }
            }

            //用户姓名上传了/删除了/重命名了文件；
            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            String _content = String.format("%s删除了成员：%s%s", _theUser.getRealname(), names, desStr);
            if (_groupids != null && _groupids.size() > 0) {
                _result++;
                _repository.sendIMMessage(_groupids, _content, userid, 1);
            }
            // }).start();
        }

        _resultResponse.setResultcode(_result);
        _resultResponse.setMessage("");
        return _resultResponse;
    }

    public List<ProjectMember> getProjectMember(ProjectMemberGetRequest _request) {
        return _repository.getProjectMember(_request);
    }

    public int deleteStage(ProjectStageDeleteRequest _request, int userid) {
        return _repository.deleteProjectStage(_request, userid);

    }

    public List<CrmProjectType> getProjectTypes() {
        return _repository.getProjectTypes();
    }

    //complete
    public int completeStage(ProjectStageStatusUpdateRequest _request, int userid) throws Exception {
        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        int _stageStatus = BaseEnum.StageStatus.Complete.getStageStatus();
        return updateProjectStageStatusSimple(_projectid, _stageid, _stageStatus, userid, _request.getIsShop());
    }

    //restart
    public int restartStage(ProjectStageStatusUpdateRequest _request, int userid) throws Exception {
        String _projectid = _request.getProjectid();
        int _stageid = _request.getStageid();
        int _stageStatus = BaseEnum.StageStatus.Start.getStageStatus();
        return updateProjectStageStatusSimple(_projectid, _stageid, _stageStatus, userid, null);
    }

    public int updateProjectStageStatusSimple(String projectid, int stageid, int stageStatus, int userid, String isShop) throws Exception {
        int _result = 0;
        try {
            _result = _repository.updateProjectStageStatusSimple(projectid, stageid, stageStatus, userid);
            if (_result > 0) {
                String _content = "";
                if (stageStatus == BaseEnum.StageStatus.Complete.getStageStatus()) {
                    if ("1".equals(isShop)) {
                        _content = "阶段已完成，群聊已关闭";
                    } else {
                        _content = "阶段已完成";
                        _content = _content + ".群聊已关闭，如需在本群聊天，请重启阶段";
                    }
                } else {
                    _content = "阶段已重启";
                }

                JSONObject obj = new JSONObject();
                JSONObject data = new JSONObject();
                obj.put("type", "system");

                data.put("type", BaseEnum.ChatType.Stage.getChatType());
                data.put("stagestatus", stageStatus);
                data.put("projectid", projectid);
                obj.put("data", data);

                _repository.SendIMGroupMessage(projectid, stageid, _content, userid, obj);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    public List<ProjectTitle> getProjectTitle(ProjectTitleGetRequest _request) {

        int projectType = _request.getProjecttype();
        int stageid = _request.getStageid();

        List<ProjectTitle> _titles = new ArrayList<>();
        List<CrmCommonItem> _results = _repository.getProjectTitle(projectType, stageid);
        for (CrmCommonItem _item : _results) {
            _titles.add(toCommonItem(_item));
        }
        return _titles;
    }

    private ProjectTitle toCommonItem(CrmCommonItem item) {

        ProjectTitle _item = new ProjectTitle();
        _item.setRecid(item.getRecid());
        _item.setRecname(item.getRecname());

        return _item;

    }

    public int saveProjectTitle(ProjectSaveTitleRequest _request, int userid) {

        return _repository.saveProjectTitle(_request, userid);

    }

    public List<ProjectInfoField> getProjectInfoFields(ProjectInfoFieldGetRequest _request, int userid) {
        List<CrmProjectInfoField> _result = _repository.getProjectInfoFields(_request, userid);
        List<ProjectInfoField> _fields = new ArrayList<>();
        for (CrmProjectInfoField _field : _result) {
            _fields.add(toProjectInfoField(_field));
        }
        return _fields;
    }


    private ProjectInfoField toProjectInfoField(CrmProjectInfoField field) {
        ProjectInfoField _field = new ProjectInfoField();
        _field.setDisplayname(field.getDisplayname());
        _field.setFieldname(field.getFieldname());
        _field.setUrl(field.getUrl());
        return _field;

    }

    public List<ProjectList> getProjectListForTask(int userid) {
        return _repository.getProjectListForTask(userid);
    }


    public ProjectSaveStageResponse saveProjectStage(ProjectStageSaveRequest _request, int userid) {
        return _repository.saveProjectStage(_request, userid);
    }

    public ProjectSaveFolderResponse saveProjectDefineFolder(ProjectSaveFolderRequest _request, int userid) {
        return _repository.saveProjectDefineFolder(_request, userid);
    }

    public List<GetAllProjectFolderResponse> getAllPorjectFolders(ProjectGetAllFolderRequest request, int userid) {
        List<GetAllProjectFolderResponse> _results = _repository.getAllPorjectFolders(request, userid);
        return _results;
    }


    public int projecFileMerge(ProjectFileMergeRequest _request, int userid) {
        int _result = _repository.projecFileMerge(_request, userid);
        return _result;
    }


    public int projectStatusChange(ProjectCompleteRequest _request, int projectStatus, int userid) {
        int _result = projectStatusChangeSimple(_request, projectStatus, userid);
        return _result;
    }

    public int projectStatusChangeSimple(ProjectCompleteRequest _request, int projectStatus, int userid) {
        String _projectid = _request.getProjectid();
        String _imGroupMessage = "";
        if (projectStatus == 1) {
            if ("1".equals(_request.getIsShop())) {
                _imGroupMessage = "项目已完成，感谢您的信任与支持！有空的话，可以到商城逛逛哦。";
            } else {
                _imGroupMessage = "项目已完成";
            }

        } else {
            _imGroupMessage = "项目已重启";
        }

        int _result = _repository.projectStatusChangeSimple(_request, projectStatus, userid);
        if (_result > 0) {

            List<CrmChatGroupPart> _chatGroups = _repository.getProjectChatGroup(_projectid);
            List<CrmChatGroup> _taskChatGroups = _commonRepository.getProjectTaskChatGroups(_projectid);
            List<String> _groupids = _chatGroups.stream().map(CrmChatGroupPart::getGroupid).collect(Collectors.toList());
            List<String> _groupids2 = _taskChatGroups.stream().map(CrmChatGroup::getGroupid).collect(Collectors.toList());
            _groupids.addAll(_groupids2);

            boolean _isActive = true;
            if (projectStatus == 1) {
                _isActive = false;
            }
            for (String id : _groupids) {
                // _commonRepository.setTaskChatGroupActive2(id,_isActive);
            }

            JSONObject obj = new JSONObject();
            JSONObject data = new JSONObject();
            obj.put("type", "system");

            data.put("type", BaseEnum.ChatType.Project.getChatType());
            data.put("stagestatus", projectStatus);
            data.put("projectid", _projectid);
            obj.put("data", data);

            _repository.SendIMGroupMessage_fix(_projectid, _imGroupMessage, userid, obj);
            //SendIMGroupMessage(_projectid, _imGroupMessage, userid);
            //?why use this way?
        }
        return _result;
    }


    public int deleteProject(ProjectCompleteRequest _request, int userid) {
        int _result = _repository.deleteProject(_request, userid);
        return _result;
    }


    public List<ProjectInfoAllFieldResponse> getProjectInfoAllFields(ProjectAllFieldRequest _request, int userid) {


        List<ProjectInfoAllFieldResponse> _fieldResult = new ArrayList<>();

        String _projectid = _request.getProjectid();
        List<CrmProject> _projects = _repository.getProject(_projectid);
        if (_projects != null) {
            int _projectType = _projects.get(0).getProjecttype();
            List<CrmProjectStage> _stages = _repository.getProjectStageList(_projectid);
            if (_stages != null) {
                for (CrmProjectStage s : _stages) {
                    ProjectInfoFieldGetRequest _fieldRequest = new ProjectInfoFieldGetRequest();
                    _fieldRequest.setProjecttype(_projectType);
                    _fieldRequest.setStageid(s.getStageid());
                    List<CrmProjectInfoField> _result = _repository.getProjectInfoFields(_fieldRequest, userid);
                    List<ProjectInfoField> _fields = new ArrayList<>();
                    for (CrmProjectInfoField _field : _result) {
                        _fields.add(toProjectInfoField(_field));
                    }
                    ProjectInfoAllFieldResponse _response = new ProjectInfoAllFieldResponse();
                    _response.setStageid(s.getStageid());
                    _response.setFields(_fields);
                    _response.setOrder(s.getOrder());
                    _fieldResult.add(_response);
                }
            }
        }

        return _fieldResult;
    }

    public int saveProjectName(ProjectSaveNameRequest _request, int userid) throws Exception {
        int _result = _repository.saveProjectName(_request, userid);
        return _result;
    }


    public int saveProjectInfo(ProjectSaveInfoRequest _request, int userid) throws Exception {
        int _result = _repository.saveProjectInfo(_request, userid);
        return _result;
    }


    public int saveProjectStageData(ProjectSaveStageRequest _request, int userid) throws Exception {
        int _result = _repository.saveProjectStageData(_request, userid);
        return _result;
    }


    public int renameProjectFile(ProjectRenameFileRequest _request, int userid) throws Exception {
        int _result = _repository.renameProjectFile(_request, userid);
        return _result;
    }

    public int deleteProjectFile(ProjectDeleteFileRequest _request, int userid) {
        int _result = _repository.deleteProjectFile(_request, userid);
        return _result;
    }

    public int addProjectFile(ProjectAddFileRequest _request, int userid) {
        int _result = _repository.addProjectFile(_request, userid);
        return _result;
    }

    public int addProjectFile2(ProjectAddFileRequest _request, int userid) {
        int _result = _repository.addProjectFile2(_request, userid);
        return _result;
    }


    @Transactional
    public int setProjectHost(ProjectSetHostRequest _request, int userid) {
        int _result = _repository.setProjectHost(_request, userid);
        return _result;
    }

    @Transactional
    public int setProjectManager(ProjectSetManagerRequest _request, int userid) {
        int _result = _repository.setProjectManager(_request, userid);
        return _result;
    }

    public List<ProjectFileFolder> getProjectFiles(GetProjectFileRequest _request, int userid) {
        return _repository.getProjectFiles(_request, userid);
    }


    public GetProjectPageItemsResponse getProjectPageItems(GetTaskPageItemsRequest _request, int userid) {
        List<CrmProject> _projects = _repository.getCrmProjectPage(_request, userid);
        PageSummary _pageSummary = _repository.getProjectPageCount(_request, userid);
        List<ProjectList> _projectInfos = _repository.getProjectInfoPage(_projects, userid);

        GetProjectPageItemsResponse _response = new GetProjectPageItemsResponse();
        _response.setPagecount(_pageSummary);
        _response.setPagedata(_projectInfos);
        return _response;
    }


    public List<ProjectList> getUnCompletedProjecs(ProjectGetListRequest _request, int userid) {

        String _searchKey = _request.getSearchkey();
        List<CrmProject> _projects = _repository.getUnCompletedProjects(_searchKey, userid);
        List<ProjectList> _projectInfos = _repository.getProjectInfoPage2(_projects, userid);
        return _projectInfos;

    }


    @Transactional
    public int setFileViewed(ProjectViewdFileRequest _request, int userid) {
        return _repository.setFileViewed(_request, userid);
    }


    @Transactional
    public int setFolderLawyerVisible(ProjectSetFolderVisibleRequest _request, int userid) {
        return _repository.setFolderLawyerVisible(_request, userid);
    }

    public GetPermissionResponse getProjectPermission(GetPermissionRequest _request, int userid) {
        return _repository.getProjectPermissions(_request, userid);
    }

    public Map<String, Object> exportProjectStageFile(ProjectStageStatusUpdateRequest _request, int userid) throws Exception {
        Map<String, Object> retData = new HashMap<String, Object>();
        String uuid = UUID.randomUUID().toString();
        String destFileId = uuid + ".docx";
        Map<String, Object> data = new HashMap<String, Object>();
        List<CrmProjectInfoExp> projectList = _repository.getProjectInfoExp(_request.getProjectid(), _request.getStageid(), userid);
        if (projectList != null && projectList.size() > 0) {
            CrmProjectInfoExp project = projectList.get(0);
            data.put("projecttype", project.getProjecttypename());
            data.put("projectname", project.getProjectname());
            data.put("projectstage", project.getStagename());

            String wtperson = "";
            String dlperson = "";
            String lsperson = "";
            List<CrmProjectLogExp> logList = new ArrayList<>();
            for (CrmProjectInfoExp info : projectList) {
                List<CrmProjectMemberExp> projectMemberList = _repository.getProjectMemberExp(info.getProjectid(), info.getStageid(), info.getGroupid(), userid);
                if (projectMemberList != null && projectMemberList.size() > 0) {
                    for (CrmProjectMemberExp m : projectMemberList) {
                        if (m.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()) {
                            if (m.getInnergrouptype() == BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType()) {
                                if (m.getIsmanager() == 1) {
                                    if (wtperson == "") {
                                        wtperson = String.format("%s（管理员）", m.getUsername());
                                    } else {
                                        wtperson += String.format("、%s（管理员）", m.getUsername());
                                    }
                                } else {
                                    if (wtperson == "") {
                                        wtperson = String.format("%s（普通成员）", m.getUsername());
                                    } else {
                                        wtperson += String.format("、%s（普通成员）", m.getUsername());
                                    }
                                }
                            } else if (m.getInnergrouptype() == BaseEnum.InnerGroupType.LawyerGroup.getInnerGroupType()) {
                                if (m.getIsmanager() == 1) {
                                    if (dlperson == "") {
                                        dlperson = String.format("%s（管理员）", m.getUsername());
                                    } else {
                                        dlperson += String.format("、%s（管理员）", m.getUsername());
                                    }
                                } else if (m.getIshost() == 1) {
                                    if (dlperson == "") {
                                        dlperson = String.format("%s（主办人）", m.getUsername());
                                    } else {
                                        dlperson += String.format("、%s（主办人）", m.getUsername());
                                    }
                                } else {
                                    if (dlperson == "") {
                                        dlperson = String.format("%s（普通成员）", m.getUsername());
                                    } else {
                                        dlperson += String.format("、%s（普通成员）", m.getUsername());
                                    }
                                }
                            }
                        } else if (m.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()) {
                            if (m.getIsmanager() == 1) {
                                if (lsperson == "") {
                                    lsperson = String.format("%s（管理员）", m.getUsername());
                                } else {
                                    lsperson += String.format("、%s（管理员）", m.getUsername());
                                }
                            } else if (m.getIshost() == 1) {
                                if (lsperson == "") {
                                    lsperson = String.format("%s（主办人）", m.getUsername());
                                } else {
                                    lsperson += String.format("、%s（主办人）", m.getUsername());
                                }
                            } else {
                                if (lsperson == "") {
                                    lsperson = String.format("%s（普通成员）", m.getUsername());
                                } else {
                                    lsperson += String.format("、%s（普通成员）", m.getUsername());
                                }
                            }
                        }
                    }
                }

                List<CrmProjectLogExp> logs = _repository.getProjectLogExp(info.getGroupid(), userid);
                if (logs != null && logs.size() > 0) {
                    logList.addAll(logs);
                }
            }

            data.put("wtperson", wtperson);
            data.put("dlperson", dlperson);
            data.put("lsperson", lsperson);

            for (CrmProjectLogExp model : logList) {
                String str = String.format("%s", model.getMsgtime());
                model.setSendtime(DateUtil.timeStamp2Date(str, null));
            }
            logList.sort(Comparator.comparing(CrmProjectLogExp::getMsgtime).reversed());
            data.put("worklog", JSONObject.toJSON(logList));

            List<CrmProjectStageInfoExp> projectStageList = _repository.getProjectStageInfoExp(project.getProjectid(), project.getStageid(), userid);

            List<Map<String, Object>> clientData = new ArrayList<>();
            List<Map<String, Object>> litigantData = new ArrayList<>();
            if (projectStageList != null && projectStageList.size() > 0) {
                for (CrmProjectStageInfoExp ps : projectStageList) {
                    if (ps.getPersontype() == BaseEnum.PersonType.Client.getPersonType()) {
                        Map<String, Object> client = new HashMap<String, Object>();
                        if (ps.getRectype() == BaseEnum.RecType.Yes.getRecType()) {
                            client.put("rectype", "自然人");
                        } else if (ps.getRectype() == BaseEnum.RecType.No.getRecType()) {
                            client.put("rectype", "非自然人");
                        }
                        client.put("title", ps.getTitle());
                        client.put("name", ps.getName());
                        client.put("phone", ps.getPhone());
                        client.put("mail", ps.getMail());
                        client.put("contact", ps.getContact());

                        clientData.add(client);
                    } else if (ps.getPersontype() == BaseEnum.PersonType.litigant.getPersonType()) {
                        Map<String, Object> litigant = new HashMap<String, Object>();
                        if (ps.getRectype() == BaseEnum.RecType.Yes.getRecType()) {
                            litigant.put("rectype", "自然人");
                        } else if (ps.getRectype() == BaseEnum.RecType.No.getRecType()) {
                            litigant.put("rectype", "非自然人");
                        }
                        litigant.put("title", ps.getTitle());
                        litigant.put("name", ps.getName());
                        litigant.put("phone", ps.getPhone());
                        litigant.put("mail", ps.getMail());
                        litigant.put("contact", ps.getContact());

                        litigantData.add(litigant);
                    }
                }
            }
            data.put("client", JSONObject.toJSON(clientData));
            data.put("litigant", JSONObject.toJSON(litigantData));

            List<Map<String, Object>> fieldData = new ArrayList<>();
            ProjectAllFieldRequest pr = new ProjectAllFieldRequest();
            pr.setProjectid(project.getProjectid());
            List<ProjectInfoAllFieldResponse> fieldList = getProjectInfoAllFields(pr, userid);
            if (fieldList != null && fieldList.size() > 0) {
                CrmProjectInfo projectInfo = _repository.getProjectInfo(project.getProjectid()).get(0);
                String projectStr = JSONObject.toJSONString(projectInfo);
                HashMap response = new Gson().fromJson(projectStr, HashMap.class);
                List<CrmProjectContactExp> projectContactList = _repository.getProjectContactExp(project.getProjectid(), project.getStageid(), userid);
                for (ProjectInfoField field : fieldList.get(0).getFields()) {
                    String showName = field.getDisplayname();
                    String fieldName = field.getFieldname();

                    if (fieldName.startsWith("client") == false && fieldName.startsWith("litigant") == false) {
                        String value = (String) response.get(field.getFieldname());
                        if (fieldName.startsWith("fullcourt")) {
                            if (projectContactList != null && projectContactList.size() > 0) {
                                List<CrmProjectContactExp> fullCourt = projectContactList.stream().filter(x -> x.getRectype() == BaseEnum.ContactType.FullCount.getContactType()).collect(Collectors.toList());
                                if (fullCourt != null && fullCourt.size() > 0) {
                                    value = fullCourt.stream().map(CrmProjectContactExp::getCombineName).collect(Collectors.joining(","));
                                }
                            }
                        } else if (fieldName.startsWith("clerk")) {
                            if (projectContactList != null && projectContactList.size() > 0) {
                                List<CrmProjectContactExp> clerk = projectContactList.stream().filter(x -> x.getRectype() == BaseEnum.ContactType.Clerk.getContactType()).collect(Collectors.toList());
                                if (clerk != null && clerk.size() > 0) {
                                    value = clerk.stream().map(CrmProjectContactExp::getCombineName).collect(Collectors.joining(","));
                                }
                            }
                        }
                        if (value == null) value = "";
                        Map<String, Object> hash = new HashMap<String, Object>();
                        hash.put("name", showName);
                        hash.put("value", value);
                        fieldData.add(hash);
                    }
                }
            }
            data.put("field", JSONObject.toJSON(fieldData));

            List<HtmlFieldMapInfo> htmlFields = new ArrayList<HtmlFieldMapInfo>();
            String _filePath = _commonHelper.getUploadFilePath();
            String templateFilePath = String.format("%s%s", _filePath, "项目工作报告.docx");

            File file = new File(_filePath, destFileId);
            WordPrintUtils f = new WordPrintUtils();
            f.ExportFile(data, htmlFields, templateFilePath, file.getAbsolutePath(), false, null, null);

            List<String> filePathList = new ArrayList<>();
            filePathList.add(_filePath + destFileId);
            List<CrmProjectFileExp> fileList = _repository.getProjectFileExp(project.getProjectid(), project.getStageid(), userid);
            if (fileList != null && fileList.size() > 0) {
                for (CrmProjectFileExp pf : fileList) {
                    String fileName = pf.getFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    String filePath = String.format("%s%s.%s", _filePath, pf.getUploadfileid(), suffix);

                    filePathList.add(filePath);
                }
            }
            String zipFilePath = String.format("%s%s.zip", _filePath, uuid);
            //TODO 解决文件重命名再考虑压缩包下载
            //FileUtils.compress(filePathList, zipFilePath, false);

            retData.put("fileid", uuid);
            retData.put("filename", String.format("%s-%s-项目工作报告.docx", project.getProjectname(), project.getStagename()));
        }

        return retData;
    }

    //end of class
}
